const webSocket = require('ws')
const path = require('path')
const fileUtils = require('../utils/file_utils')

const wss = new webSocket.Server({
  port: 9998,
})

module.exports.listen = function () {
  wss.on('connection', (socket) => {
    console.log('有连接')
    socket.on('message', async (msg) => {
      console.log('有消息', msg)

      // ws 8.4.0 版本中，此处的 msg 是 Buffer。可以用 toString('utf8') 的方式转成字符串。JSON.stringify 也可以。
      // const stringMsg = msg.toString('utf8')
      // console.log('stringMsg', stringMsg)
      // let payload = JSON.parse(stringMsg)

      let payload = JSON.parse(msg)
      if (payload.action === 'getData') {
        let filePath = '../data/' + payload.chartName + '.json'
        filePath = path.join(__dirname, filePath)
        const data = await fileUtils.getFileJsonData(filePath)
        payload.data = data
        socket.send(JSON.stringify(payload))
      } else {
        wss.clients.forEach((client) => {
          // 要注意这里发送的数据是字符串还是 Buffer
          // client.send(msg) // 既然上面是 send 字符串的内容，这里不应该 send msg
          client.send(JSON.stringify(payload))
        })
      }
    })
  })
}
